package com.cygnus.redis;

import com.cygnus.dao.EmployeeMapper;
import com.cygnus.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
/*
String类型测试
通过KEY得到VALUE
先在REDIS查询，没有再去MYSQL查询
在MYSQL中查询到后，先存到REDIS中，再返回
 */
public class RedisService {
    @Resource
    RedisTemplate redisTemplate;
    @Autowired
    EmployeeMapper employeeMapper;
//    @Resource(name = "redisTemplate")
//    HashOperations<String,Integer,Employee> hash;
//    @Resource(name = "redisTemplate")
//    ListOperations list;


    public String getString(String key) {
        ValueOperations<String, String> str = redisTemplate.opsForValue();
        if (redisTemplate.hasKey(key)){
            System.out.println("redis中取出：");
            redisTemplate.expire(key, 10, TimeUnit.MINUTES);
            return str.get(key);
        }
        else {
            Employee employee = employeeMapper.selectByPrimaryKey(Integer.parseInt(key));
            str.set(key, employee.toString());
            System.out.println("mySQL中取出并返回：");
            return employee.toString();
        }
    }

    public Employee getHash(Integer id) {
        HashOperations<String,Object,Employee> hash = redisTemplate.opsForHash();
        if (hash.hasKey(Employee.getName(),id.toString())){
            Employee emp =  hash.get(Employee.getName(), id.toString());
            System.out.println("REDIS已有："+emp);
            return emp;
        }
        else {
            Employee employee = employeeMapper.selectByPrimaryKey(id);
            hash.put(Employee.getName(), id.toString(), employee);
            System.out.println("MYSQL找到："+Employee.getName()+employee+"\n并存入REDIS");
            return employee;
        }
    }

    public void listGet(String key) {
        ListOperations<String,String> list = redisTemplate.opsForList();
        list.rightPush(key, "周神月薪8000");
        list.rightPushAll(key, "杨欢公主买房","吴雨薇送逼","周兵猪狗不如贱畜","光腿穿裙发骚","大长腿骚逼","弘扬正能量","不放初心","跟党走");
    }

    public List<String> listRange(String key, Integer start, Integer end) {
        ListOperations<String,String> list = redisTemplate.opsForList();
        List<String> range = list.range(key, start, end);
        return range;
    }

    public List<String> listPage(String key, Integer pageNum, Integer pageSize) {
        ListOperations<String,String> list = redisTemplate.opsForList();
        Integer start=(pageNum-1)*pageSize;
        Integer end=start+pageSize-1;
        List<String> range = list.range(key, start, end);
        return range;
    }
    // 1,2,3,4,5,6,7,8,9
}
